// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import Credentials from "next-auth/providers/credentials"
import bcrypt from 'bcrypt'
import {PrismaAdapter} from "@auth/prisma-adapter";
import {prisma} from "@/lib/db"

// 导出让其他服务器组件可以获取
export const authOptions = {
    adapter: PrismaAdapter(prisma),
    providers: [
        // GoogleProvider({
        //     clientId: process.env.GOOGLE_CLIENT_ID!,
        //     clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
        // })
        Credentials({
            name: 'Credentials',
            // You can specify which fields should be submitted, by adding keys to the `credentials` object.
            // e.g. domain, username, password, 2FA token, etc.
            credentials: {
                email: {label: 'Username', type: 'email', placeholder: "邮箱"},
                password: {label: 'Password', type: 'password', placeholder: "密码"},
            },
            // 登录验证方法
            authorize: async (credentials) => {
                let email = credentials!.email
                let password = credentials!.password
                if (!email || !password) return null

                // 查询数据库
                const user = await prisma.user.findUnique({where: {email}})

                console.log(user)
                if (!user) return null

                const passwordMatch = await bcrypt.compare(password, user.hashedPassword)

                return passwordMatch ? user : null
            },
        }),
    ],
    session: {
        strategy: 'jwt'
    }
}
export const handler = NextAuth(authOptions)

export {handler as GET, handler as POST}